package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.attr.Attrs
import com.gitee.wsl.doc.prosemirror.model.content.ext.findWrapping
import com.gitee.wsl.doc.prosemirror.model.node.NodeType
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.transform.ext.wrap

class WrapIn(val nodeType: NodeType, val attrs: Attrs? = null): Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val selection = state.selection
        val from = selection._from
        val to = selection._to

        val range = from.blockRange(to)
        val wrapping = range?.findWrapping(nodeType, attrs) ?: return false

        dispatch?.invoke(state.tr.wrap(range, wrapping).scrollIntoView())
        return true
    }
}

fun Command.Companion.wrapIn(
    nodeType: NodeType,
    attrs: Attrs? = null
) = WrapIn(nodeType,attrs)